package com.rmondjone.androidcamerademo

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.text.Html
import android.util.Log
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.rmondjone.utils.dp

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */

public class MyImageGetter(val textView: TextView, val resources: Resources) : Html.ImageGetter {
    override fun getDrawable(source: String?): Drawable? {


        Log.e("msg", "图片-------------" + source)
        val urlDrawable = MyBitMapDrawle(resources, null)

        Glide.with(MyApplication.application).asBitmap().load(source).listener(object : RequestListener<Bitmap> {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: com.bumptech.glide.request.target.Target<Bitmap>?, isFirstResource: Boolean): Boolean {
                return true

            }

            override fun onResourceReady(resource: Bitmap?, model: Any?, target: com.bumptech.glide.request.target.Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                resource?.let {
                    Log.e("msg", "加载完成图片-------------" + source)
                    urlDrawable.myBitmap = resource
                    urlDrawable.setBounds(0, 30.dp.toInt(), resource.width, resource.height);
                    textView.text = textView.text;
                }
                return true
            }

        }).submit()

        return urlDrawable

    }

}

class MyBitMapDrawle(res: Resources, var myBitmap: Bitmap?) : BitmapDrawable(res, myBitmap) {


    override fun draw(canvas: Canvas) {
        super.draw(canvas)


        myBitmap?.let {
            canvas.drawBitmap(it, 0f, 0f, paint)
//            canvas.drawBitmap(it, null, Rect(0, 0, it.width, it.height), paint);
        }
    }

}